import { Global, Module } from '@nestjs/common';
import { ConfigModule, ConfigType } from '@nestjs/config';
import { drizzle } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise';

import databaseConfig from '../config/database.config';
import { DRIZZLE_CONNECTION } from './constants/database.constants';
import { isDevelopment } from '@common/utils/env.util';

@Global()
@Module({
  imports: [ConfigModule],
  providers: [
    {
      provide: DRIZZLE_CONNECTION,
      inject: [databaseConfig.KEY],
      useFactory: async (config: ConfigType<typeof databaseConfig>) => {
        // Create MySQL connection
        const connection = await mysql.createConnection({
          host: config.host,
          port: config.port,
          user: config.username,
          password: config.password,
          database: config.database,
        });

        // Wrap with Drizzle
        return drizzle(connection, {
          logger: isDevelopment(),
        });
      },
    },
  ],
  exports: [DRIZZLE_CONNECTION],
})
export class DatabaseModule {}